const db = require("../utils/db");
const util = require("../utils/util.js");
//获取文章列表
exports.getArticleList = async (ctx) => {
  let search = ctx.query.search || "";
  let keyword = ctx.query.keyword || "";
  let state = ctx.query.state || "";
  let likes = ctx.query.likes || "";
  let tag_id = ctx.query.tag_id || "";
  let category_id = ctx.query.category_id || "";
  let article = ctx.query.article || "";
  let pageNum = parseInt(ctx.query.pageNum) || 1;
  let pageSize = parseInt(ctx.query.pageSize) || 10;
  let author = ctx.query.author || "";
  // 如果是文章归档 返回全部文章
  if (article) {
    pageSize = 1000;
  }
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  let responseData = {
    count: 0,
    list: [],
  };

  //获取整个article列表
  let res = await new Promise((resolve, reject) => {
    let sqlLang = `select id,title,author,descri,img_url,tags,meta,create_time,keyword from article`;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      else {
        responseData.count = data.length;
        resolve(data);
      }
    });
  });
  let newList = [];
  //我的文章
  if (author && search) {
    res.forEach((e) => {
      if (e.author === author) {
        if (e.keyword.indexOf(search) != -1) {
          newList.unshift(e);
        } else if (e.title.indexOf(search) != -1) {
          newList.push(e);
        } else {
          // console.log('3')
          //forEach不能用break,continue
          let tag = JSON.parse(e.tags);
          //  console.log(tag)
          for (let i = 0; i < tag.length; i++) {
            if (tag.indexOf(search) != -1) {
              newList.unshift(e);
              break;
            }
          }
        }
      }
    });
    let len = newList.length;
    responseData.count = len;
    responseData.list = newList;
  } else if (author) {
    res.forEach((e) => {
      if (e.author === author) {
        newList.push(e);
      }
    });
    responseData.list = newList;
  } else if (likes) {
    // 根据热度 likes 返回数据
    res.sort((a, b) => {
      return b.meta.likes - a.meta.likes;
    });
    responseData.list = res;
    // responseData.count=res.length
  } else if (tag_id) {
    // 根据标签 id 返回数据
    res.forEach((item) => {
      if (item.tags.indexOf(tag_id) > -1) {
        newList.push(item);
      }
    });
    let len = newList.length;
    responseData.count = len;
    responseData.list = newList;
  } else if (article) {
    //文章归档
    const archiveList = [];
    let obj = {};
    // 按年份归档 文章数组
    res.forEach((e) => {
      let year = e.create_time.getFullYear();
      // let month = e.create_time.getMonth()
      if (!obj[year]) {
        obj[year] = [];
        obj[year].push(e);
      } else {
        obj[year].push(e);
      }
    });
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        const element = obj[key];
        let item = {};
        item.year = key;
        item.list = element;
        archiveList.push(item);
      }
    }
    archiveList.sort((a, b) => {
      return b.year - a.year;
    });
    // responseData.count=archiveList.length
    responseData.list = archiveList;
  } else if (search) {
    //文章搜索
    //  console.log(search)
    //关键字包含的排行前面，只有标题包含的排后面
    // console.log(typeof item.keyword)
    //"vue".indexOf("vue")是0,不符合返回的是-1
    // console.log("search!")

    for (let j = 0; j < res.length; j++) {
      if (res[j].keyword.indexOf(search) != -1) {
        newList.unshift(res[j]);
      } else if (res[j].title.indexOf(search) != -1) {
        //  console.log('2')
        //  console.log(item.title)
        newList.push(res[j]);
      } else {
        // console.log('3')
        //forEach不能用break,continue
        let tag = JSON.parse(res[j].tags);
        //  console.log(tag)
        for (let i = 0; i < tag.length; i++) {
          if (tag.indexOf(search) != -1) {
            newList.unshift(res[j]);
            break;
          }
        }
      }
    }

    let len = newList.length;
    responseData.count = len;
    responseData.list = newList;
  } else {
    // responseData.count=res.length
    responseData.list = res;
  }
  util.responseClient(ctx, 200, 0, "操作成功！", responseData);
};
//获取文章详情
exports.getArtiDetail = async (ctx) => {
  let { id } = ctx.request.body;
  if (!id) {
    util.responseClient(ctx, 200, 1, "文章不存在 ！");
    return;
  }
  //查找文章
  let res = await new Promise((resolve, reject) => {
    let sqlLang = `select * from article where id='${id}' `;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (res) {
    //观看人数+1
    let cnt = 1 + parseInt(JSON.parse(res[0].meta).views);
    await new Promise((resolve, reject) => {
      // let sqlLang = `update article set meta='${res[0].meta}' where id='${id}' `;
      let sqlLang = `update article set meta = JSON_REPLACE(meta, '$.views', '${cnt}') where id ='${id}'`;
      return db.query(sqlLang, (err, data) => {
        if (err) throw err;
        console.log(data);
        resolve(data);
      });
    });
    //把comments转成object
    if (res[0].tags) {
      res[0].tags = JSON.parse(res[0].tags);
    }
    if (res[0].comments) {
      res[0].comments = JSON.parse(res[0].comments);
    }
    if (res[0].likes_users) {
      res[0].likes_users = JSON.parse(res[0].likes_users);
    }
    if (res[0].meta) {
      res[0].meta = JSON.parse(res[0].meta);
    }
    util.responseClient(ctx, 200, 0, "操作成功 ！", res[0]);
  }
};
//新增文章
exports.addArticle = async (ctx) => {
  const { title, author, keyword, content, descri, img_url, tags } =
    ctx.request.body;
  let insertLang;
  let len = content.length;
  let tag = JSON.stringify(tags ? tags : []);
  let meta = {
    likes: 0,
    views: "0",
    comments: 0,
  };
  let time = util.timestampToTime(new Date());
  console.log(util.timestampToTime(new Date()));
  if (img_url) {
    insertLang = `insert into article (title,author,keyword,content,descri,img_url,tags,numbers,views,create_time,update_time) values ('${title}', '${author}', '${keyword}', '${content}', '${descri}','${img_url}','${tag}','${len}','${views}','${time}','${time}')`;
  } else {
    insertLang = `insert into article (title,author,keyword,content,descri,tags,numbers,meta,create_time,update_time) values ('${title}', '${author}', '${keyword}', '${content}', '${descri}','${tag}','${len}','${JSON.stringify(
      meta
    )}','${time}','${time}')`;
  }
  // 找不到对应的账号，直接插入一个
  let newArticle = await new Promise((resolve, reject) => {
    // 生成token name, password, phone, email, introduce, type
    // const token = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, 'secret', { expiresIn: 3600 })
    return db.query(insertLang, (error, data) => {
      if (error) throw error;
      // 已插入数据，
      resolve(data);
    });
  });
  if (newArticle) {
    util.responseClient(ctx, 200, 0, "保存成功", newArticle);
  } else {
    util.responseClient(ctx, 200, 0, "保存失败！");
  }
};
//文章编辑
exports.updateArticle = async (ctx) => {
  const { id, title, author, keyword, content, descri, tags } =
    ctx.request.body;
  let article_id = parseInt(id);
  // console.log(article_id)
  let tag = JSON.stringify(tags ? tags : []);
  let time = util.timestampToTime(new Date());
  // let key =JSON.stringify( keyword ? keyword.split(',') : [])
  //查找文章
  let article = await new Promise((resolve, reject) => {
    let sqlLang = `select * from article where id='${article_id}' `;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (!article) {
    util.responseClient(ctx, 200, 1, "文章不存在 ！");
    return;
  }
  // console.log(article)
  if (article) {
    let res = await new Promise((resolve, reject) => {
      // let sqlLang = `update article set meta='${res[0].meta}' where id='${id}' `;
      let sqlLang = `update article set title='${title}',author='${author}',keyword='${keyword} ',content='${content}',descri='${descri}',tags='${tag}',update_time='${time}' where id ='${article_id}'`;
      return db.query(sqlLang, (err, data) => {
        if (err) throw err;
        resolve(data);
      });
    });
    if (res) {
      util.responseClient(ctx, 200, 0, "编辑成功！");
    }
  }
};
// 文章点赞
exports.likeArticle = async (ctx) => {
  let { article_id, user_id } = ctx.request.body;
  console.log(article_id, user_id);
  // 验证用户是否已经在数据库中
  let res = await new Promise((resolve, reject) => {
    let sqlLang = `select * from user where id='${user_id}'`;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (!res) {
    util.responseClient(ctx, 200, 1, "用户不存在");
    return;
  }
  //更新观看人数
  let article = await new Promise((resolve, reject) => {
    let sqlLang = `select * from article where id='${article_id}' `;
    return db.query(sqlLang, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (!article) {
    util.responseClient(ctx, 200, 1, "该文章不存在！");
    return;
  }
  if (article) {
    //观看人数+1
    let cnt = 1 + parseInt(JSON.parse(article[0].meta).likes);
    let time = util.timestampToTime(new Date());
    await new Promise((resolve, reject) => {
      // let sqlLang = `update article set meta='${res[0].meta}' where id='${id}' `;JSON.stringify(me
      let sqlLang = `update article set meta = JSON_REPLACE(meta, '$.likes', '${cnt}')  where id='${article_id}' `;
      return db.query(sqlLang, (err, data) => {
        if (err) throw err;
        resolve(data);
      });
    });
  }
  util.responseClient(ctx, 200, 0, "操作成功 ！");
};
